package com.twotigers.tenthpower.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.twotigers.tenthpower.entity.TbCity;
import com.twotigers.tenthpower.service.ITbCityService;
import io.renren.common.utils.IdWorker;
import io.renren.common.utils.Result;
import io.renren.common.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 城市 前端控制器
 * </p>
 *
 * @author ice
 * @since 2021-03-05
 */
@RestController
@RequestMapping("/city")
@CrossOrigin
public class TbCityController {

    @Autowired
    private ITbCityService cityService;

    @Autowired
    private IdWorker idWorker;

    //返回城市列表
    @GetMapping
    public Result list() {
        return new Result(true, StatusCode.OK, "返回城市列表",cityService.list());
    }

    //新增城市
    @PostMapping
    public Result add(@RequestBody TbCity tbCity) {
        tbCity.setId(idWorker.nextId()+"");
        cityService.save(tbCity);
        return new Result(true, StatusCode.OK, "新增城市");
    }

    //根据id查询
    @GetMapping("/{cityId}")
    public Result findOne(@PathVariable("cityId") String id) {
        TbCity city = cityService.findOne(id);
        return new Result(true, StatusCode.OK, "根据id查询",city);
    }

    //修改城市
    @PutMapping("/{cityId}")
    public Result upd(@PathVariable("cityId") String id,@RequestBody TbCity city) {
        city.setId(id);
        cityService.updateById(city);
        return new Result(true, StatusCode.OK, "修改城市");
    }

    //删除城市
    @DeleteMapping("/{cityId}")
    public Result del(@PathVariable("cityId") String id) {
        cityService.removeById(id);
        return new Result(true, StatusCode.OK, "删除城市");
    }

    //根据条件查询城市列表
    @PostMapping("/search")
    public Result find(@RequestBody TbCity city) {
        List<TbCity> cityList = cityService.find(city);
        return new Result(true, StatusCode.OK, "根据条件查询城市列表",cityList);
    }

    //根据条件查询城市列表 + 分页
    @PostMapping("/search/{page}/{size}")
    public Result fenye(@RequestBody TbCity city, @PathVariable("page") int page, @PathVariable("size") int size) {
        IPage<TbCity> iPage = cityService.fenye(city, page, size);
        long total = iPage.getTotal();
        List<TbCity> records = iPage.getRecords();

        HashMap<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("rows", records);

        return new Result(true, StatusCode.OK, "根据条件查询城市列表",map);
    }

}
